package org.dromara.common.mybatis.core.mapper;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.dromara.common.core.utils.MapstructUtils;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 自定义 Mapper 接口, 实现 自定义扩展
 *
 * @param <T> table 泛型
 *
 *
 * @since 2021-05-13
 */
@SuppressWarnings("unchecked")
public interface BaseMapper<T> extends com.baomidou.mybatisplus.core.mapper.BaseMapper<T> {

  Log log = LogFactory.getLog(BaseMapper.class);

  default List<T> selectList() {
    return this.selectList(new QueryWrapper<>());
  }

  /**
   * 批量插入
   */
  default boolean insertBatch(Collection<T> entityList) {
    return Db.saveBatch(entityList);
  }

  /**
   * 批量更新
   */
  default boolean updateBatchById(Collection<T> entityList) {
    return Db.updateBatchById(entityList);
  }

  /**
   * 批量插入或更新
   */
  default boolean insertOrUpdateBatch(Collection<T> entityList) {
    return Db.saveOrUpdateBatch(entityList);
  }

  /**
   * 批量插入(包含限制条数)
   */
  default boolean insertBatch(Collection<T> entityList, int batchSize) {
    return Db.saveBatch(entityList, batchSize);
  }

  /**
   * 批量更新(包含限制条数)
   */
  default boolean updateBatchById(Collection<T> entityList, int batchSize) {
    return Db.updateBatchById(entityList, batchSize);
  }

  /**
   * 批量插入或更新(包含限制条数)
   */
  default boolean insertOrUpdateBatch(Collection<T> entityList, int batchSize) {
    return Db.saveOrUpdateBatch(entityList, batchSize);
  }

  /**
   * 插入或更新(包含限制条数)
   */
  default boolean insertOrUpdate(T entity) {
    return Db.saveOrUpdate(entity);
  }


  /**
   * 查询（根据ID 批量查询）
   */
  default <C> List<C> selectVoBatchIds(Collection<? extends Serializable> idList, Class<C> voClass) {
    List<T> list = this.selectBatchIds(idList);
    if (CollUtil.isEmpty(list)) {
      return CollUtil.newArrayList();
    }
    return MapstructUtils.convert(list, voClass);
  }

  /**
   * 查询（根据 columnMap 条件）
   */
  default <C> List<C> selectVoByMap(Map<String, Object> map, Class<C> voClass) {
    List<T> list = this.selectByMap(map);
    if (CollUtil.isEmpty(list)) {
      return CollUtil.newArrayList();
    }
    return MapstructUtils.convert(list, voClass);
  }


  default <C> List<C> selectObjs(Wrapper<T> wrapper, Function<? super Object, C> mapper) {
    return this.selectObjs(wrapper).stream().filter(Objects::nonNull).map(mapper).collect(Collectors.toList());
  }

}
